package com.avalon.shop.service;

import com.avalon.core.condition.Condition;
import com.avalon.core.field.Field;
import com.avalon.core.field.Fields;
import com.avalon.core.model.Record;
import com.avalon.core.model.RecordRow;
import com.avalon.core.service.AbstractService;
import com.avalon.shop.model.MediaCheckAsyncResponse;
import com.avalon.shop.model.WxaMediaCheckMsgResult;
import com.avalon.shop.service.wx.WeiXinShopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WxCheckRecordService extends AbstractService {
    private final WeiXinShopService weiXinShopService;
    @Value("${wx.fileUrl:}")
    private String fileUrl;
    private final ShareService shareService;
    private final PetAdoptService petAdoptService;

    public WxCheckRecordService(WeiXinShopService weiXinShopService,
                                ShareService shareService,
                                @Lazy PetAdoptService petAdoptService) {
        this.weiXinShopService = weiXinShopService;
        this.shareService = shareService;
        this.petAdoptService = petAdoptService;
    }

    @Override
    public String getServiceName() {
        return "wx.check.record";
    }

    @Override
    public Boolean needDefaultNameField() {
        return false;
    }

    @Override
    public Boolean getNeedDefaultField() {
        return false;
    }

    public final Field fromSrcId = Fields.createInteger("来源id");
    public final Field fromSrcModel = Fields.createString("来源模型");
    public final Field traceId = Fields.createString("审核id");
    public final Field openId = Fields.createString("微信用户id");
    public final Field errCode = Fields.createString("创建任务结果");
    public final Field errMsg = Fields.createString("创建任务描述");

    public final Field resultSuggest = Fields.createString("综合结果建议");
    public final Field resultLabel = Fields.createInteger("综合结果命中标签枚举值"); // 100 正常；20001 时政；20002 色情；20006 违法犯罪；21000 其他

    /**
     * 分享图片审核
     *
     * @param shareId
     * @param media_url
     */
    public void createShareCheckRecord(Integer shareId, String openId, String media_url) {
        log.info("createShareCheckRecord shareId:" + shareId + " media_url:" + media_url);
        MediaCheckAsyncResponse response = weiXinShopService.check_image_forum(openId, fileUrl + media_url);

        RecordRow recordRow = new RecordRow();
        recordRow.put(fromSrcId, shareId);
        recordRow.put(fromSrcModel, "pet.share");
        recordRow.put(this.openId, openId);
        recordRow.put("traceId", response.getTrace_id());
        recordRow.put(errCode, response.getErrcode());
        recordRow.put(errMsg, response.getErrmsg());
        recordRow.put(resultLabel, "-1");
        insert(recordRow);
        if (response.getErrcode() != 0) {
            shareService.updateCheckFailState(shareId);
        }
    }

    public void createAdoptCheckRecord(Integer adoptId, String openId, String media_url) {
        log.info("createAdoptCheckRecord adoptId->{},media_url->{},openId->{}", adoptId, media_url, openId);
        MediaCheckAsyncResponse response = weiXinShopService.check_image_forum(openId, fileUrl + media_url);

        RecordRow recordRow = new RecordRow();
        recordRow.put(fromSrcId, adoptId);
        recordRow.put(fromSrcModel, "pet.adopt");
        recordRow.put(this.openId, openId);
        recordRow.put("traceId", response.getTrace_id());
        recordRow.put(errCode, response.getErrcode());
        recordRow.put(errMsg, response.getErrmsg());
        recordRow.put(resultLabel, "-1");
        insert(recordRow);
        if (response.getErrcode() != 0) {
            petAdoptService.updateCheckFailState(adoptId);
        }
    }


    public void updateShareCheckRecord(String traceId, WxaMediaCheckMsgResult result) {
        Record select = select(this.traceId.eq(traceId), "id", "fromSrcId", "fromSrcModel");
        RecordRow recordRow = null;
        if (select.isEmpty()) {
            return;
        }
        recordRow = select.get(0);
        recordRow.put("resultSuggest", result.getSuggest());
        recordRow.put("resultLabel", result.getLabel());
        update(recordRow);

        if (recordRow.getString("fromSrcModel").equals("pet.share")) {
            checkShareState(recordRow.getInteger("fromSrcId"));
        } else if ("pet.adopt".equals(recordRow.getString("fromSrcModel"))) {
            checkAdoptState(recordRow.getInteger("fromSrcId"));
        }
    }

    public void checkShareState(Integer shareId) {
        Integer count = selectCount(fromSrcId.eq(shareId));
        Integer labelCount = selectCount(fromSrcId.eq(shareId).andEqualCondition(resultLabel, 100)); // 成功的个数
        String state = "check";
        if (count.equals(labelCount)) {
            state = "success";
        } else {
            Condition failCondition = Condition.notEqualCondition(resultLabel, -1).andNotEqualCondition(resultLabel, 100);
            Integer failCount = selectCount(fromSrcId.eq(shareId).andCondition(failCondition));// 失败个数
            if (!failCount.equals(0)) {
                state = "fail";
            }
        }
        shareService.checkShareState(shareId, state);
    }

    public void checkAdoptState(Integer adoptId) {
        Integer count = selectCount(fromSrcId.eq(adoptId));
        Integer labelCount = selectCount(fromSrcId.eq(adoptId).andEqualCondition(resultLabel, 100)); // 成功的个数
        String state = "check";
        if (count.equals(labelCount)) {
            state = "success";
        } else {
            Condition failCondition = Condition.notEqualCondition(resultLabel, -1).andNotEqualCondition(resultLabel, 100);
            Integer failCount = selectCount(fromSrcId.eq(adoptId).andCondition(failCondition));// 失败个数
            if (!failCount.equals(0)) {
                state = "fail";
            }
        }
        petAdoptService.checkAdoptState(adoptId, state);
    }
}
